package cn.wolfcode.p2p.bussness.service.impl;

import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.bussness.domain.PaymentScheduleDetail;
import cn.wolfcode.p2p.bussness.domain.SystemAccount;
import cn.wolfcode.p2p.bussness.domain.SystemAccountFlow;
import cn.wolfcode.p2p.bussness.mapper.SystemAccountMapper;
import cn.wolfcode.p2p.bussness.service.ISystemAccountFlowService;
import cn.wolfcode.p2p.bussness.service.ISystemAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class SystemAccountServiceImpl implements ISystemAccountService {

    @Autowired
    private SystemAccountMapper systemAccountMapper;

    @Autowired
    private ISystemAccountFlowService systemAccountFlowService;

    @Override
    public int save(SystemAccount systemAccount) {
        return systemAccountMapper.insert(systemAccount);
    }

    @Override
    public int update(SystemAccount systemAccount) {
        int count = systemAccountMapper.updateByPrimaryKey(systemAccount);
        //乐观锁处理
        if (count == 0) {
            throw new DisplayableException("乐观锁异常,systemAccountId: " + systemAccount.getId());
        }
        return count;
    }

    @Override
    public SystemAccount get() {
        return systemAccountMapper.selectByCurrent();
    }

    /**
     * 初始化系统账户
     */
    @Override
    public void initSystemAccount() {
        SystemAccount systemAccount = this.get();
        if(systemAccount == null){
            //创建一个系统账户出来
            systemAccount = new SystemAccount();
            //并保存到数据库
            this.save(systemAccount);
        }
    }

    @Override
    public void payInterest(PaymentScheduleDetail psd) {
        //获取系统账户
        SystemAccount systemAccount = this.get();
        //减少可用余额
        systemAccount.setUsableAmount(systemAccount.getUsableAmount().subtract(psd.getInterest()));
        //生成流水
        SystemAccountFlow flow = new SystemAccountFlow();
        flow.setUsableAmount(systemAccount.getUsableAmount());
        flow.setActionTime(new Date());
        flow.setActionType(Constants.SYSTEM_ACCOUNT_ACTIONTYPE_EXPACCOUNT_MANAGE_CHARGE);
        flow.setAmount(psd.getInterest());
        flow.setFreezeAmount(systemAccount.getFreezedAmount());
        flow.setNote("xxxx体验标结算,支付利息: " + psd.getInvestorId() + "元");
        this.update(systemAccount);
        systemAccountFlowService.save(flow);
    }
}
